package com.sxz.sbs.applibrary.banner;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AccelerateInterpolator;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.sxz.sbs.applibrary.R;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 
* @ClassName: AutoSlippingViewPager 
* @Description: (自动滚动广告图空间 )
 */
public class AutoSlippingViewPager extends LinearLayout {

	public AutoSlippingViewPager(Context context, AttributeSet attrs) {
		super(context, attrs);
		init(context);
	}

	public AutoSlippingViewPager(Context context) {
		super(context);
		init(context);
	}

	public AutoSlippingViewPager(Context context, AttributeSet attrs, int defStyleAttr) {
		super(context, attrs, defStyleAttr);
		init(context);
	}

	private static Bitmap def_bitmap;//还没下载的时候显示默认的图片
	private RelativeLayout rlRootView;// 根视图
	private ViewPager viewPager;// 存放View的ViewPager对象
	private FixedSpeedScroller mScroller;
	private AutoSlippingViewPagerIndicator viewPagerIndicator;// 用来指示当前第几张图片
	private AdsPageAdapter adapter;
	private boolean autoLooper = true;// 自动循环
	private boolean autoPlay = true;// 自动播放
	private Message message;
	private AutoPlayHandler autoPlayHandler;
	private static int LOOPER_TIME = 5000;
	private static int VIEWPAGER_TIME = 1000;
	private static int SCROLL_TIME = 100;
	private TextView numIndicator;
	private RelativeLayout rlBottom;
	private IndicatorStyle style = IndicatorStyle.NORMAL;
	/** 底部显示图片标题的TextView */
	private TextView tvTitle;
	private RequestOptions options;
	@SuppressWarnings("deprecation")
	private void init(final Context context) {
		options = new RequestOptions().placeholder(R.drawable.img_banner)
		.error(R.drawable.img_banner);
		LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		rlRootView = (RelativeLayout) inflater.inflate(R.layout.layout_auto_slipping_view_pager, null);
		this.addView(rlRootView);
		tvTitle = (TextView) rlRootView.findViewById(R.id.tvTitle);
		viewPager = (ViewPager) rlRootView.findViewById(R.id.my_view_pager);
		numIndicator = (TextView) rlRootView.findViewById(R.id.numIndicator);
		rlBottom = (RelativeLayout) rlRootView.findViewById(R.id.rl_bottom);
		//=============================================
		//反射viewPager里面的mScroller
		try {
			Field mField = ViewPager.class.getDeclaredField("mScroller");
			mField.setAccessible(true);
			mScroller = new FixedSpeedScroller(viewPager.getContext(), new AccelerateInterpolator());
			mField.set(viewPager, mScroller);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		//=============================================
		viewPagerIndicator = (AutoSlippingViewPagerIndicator) rlRootView.findViewById(R.id.view_pager_indicator);
		viewPager.setOnPageChangeListener(new OnPageChangeListener() {
			@Override
			public void onPageSelected(int position) {
				if (style == IndicatorStyle.NORMAL) {
					if (position == 0) {
						viewPagerIndicator.setCurrentPageIndicator(viewPagerIndicator.getIndicatorCount() - 1);
					} else if (position == viewPager.getAdapter().getCount() - 1) {
						viewPagerIndicator.setCurrentPageIndicator(0);
					} else {
						viewPagerIndicator.setCurrentPageIndicator(position - 1);
					}
					//	tvTitle.setText(adapter.getPageTitle(position));
				} else if (style == IndicatorStyle.NUMBER) {
					if (position == 0) {
						numIndicator.setText((1)+"/"+viewPagerIndicator.getIndicatorCount());
					} else if (position == viewPager.getAdapter().getCount() - 1) {
						numIndicator.setText((1)+"/"+viewPagerIndicator.getIndicatorCount());
					} else {
						numIndicator.setText(position+"/"+viewPagerIndicator.getIndicatorCount());
					}

				}

			}

			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {
			}

			@Override
			public void onPageScrollStateChanged(int state) {
				if (state == ViewPager.SCROLL_STATE_IDLE) {
					int pageCount = adapter.getCount();
					int curr = viewPager.getCurrentItem();
					if (curr == 0) {
						if (null != mScroller) {
							mScroller.setDuration(VIEWPAGER_TIME);
						}
						viewPager.setCurrentItem(pageCount - 2, false);
					} else if (curr == pageCount - 1) {
						if (null != mScroller) {
							mScroller.setDuration(VIEWPAGER_TIME);
						}
						viewPager.setCurrentItem(1, false);
					}
					adapter.notifyDataSetChanged();
					canScroll = true;//滑动完成可以保证滑动其他view的时候响应手势返回
				}
			}
		});

		viewPager.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// 在这里做手势的判断
				// 如果是左边滑动

				// 记住手指点下去的那个点
				// 判断移动的位置和距离
				switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN:

					DOWN_X = event.getX();
					DOWN_Y = event.getY();
					if (autoPlayHandler != null) {
						autoPlayHandler.removeMessages(0);
						if (null != mScroller) {
							mScroller.setDuration(SCROLL_TIME);
						}
					}
					break;
				case MotionEvent.ACTION_MOVE:
					float currentX = event.getX();
					float currentY = event.getY();

					if ((Math.abs((DOWN_Y - currentY)) > VERTICAL_DISTANCE && Math.abs(DOWN_X - currentX) < HORIZONTAL_DISTANCE)// 上下滑动
							|| (adapter != null && adapter.getCount() == 3)) {
						v.getParent().requestDisallowInterceptTouchEvent(false);
						return true;
					}
					break;

				case MotionEvent.ACTION_UP:// 如果按下的地方和手指起来的地方在一起的话就认为是用户进行了点击
					startAutoSlipping();
					if (null != onPageItemClickListener) {
						if (Math.abs(event.getX() - DOWN_X) < 30 && Math.abs(event.getY() - DOWN_Y) < 30) {
							onPageItemClickListener.onItemClicked(viewPager.getCurrentItem());
						}
					}
					break;

				default:
					break;
				}
				if (adapter != null && adapter.getCount() > 3) {//添加手势返回的操作判断
					canScroll = false;
				} else {
					canScroll = true;
				}
				v.getParent().requestDisallowInterceptTouchEvent(true);//
				return false;
			}
		});

	}

	private boolean canScroll = true;

	public boolean canScrollBack() {//添加只有一个轮播图的时候可以响应手势滑动返回
		return canScroll;
	}

	private float DOWN_X = 0;
	private float DOWN_Y = 0;
	private static final int HORIZONTAL_DISTANCE = 30;
	private static final int VERTICAL_DISTANCE = 50;

	/**
	 * 隐藏整个根视图
	 * */
	public void hideRootView() {
		rlRootView.setVisibility(View.GONE);
	}

	/**
	 * 显示整个根视图
	 * */
	public void showRootView() {
		rlRootView.setVisibility(View.VISIBLE);
	}

	private List<Object> headerViews;

	private List<Integer> headerView;

	/**
	 * 设置ViewPager中的每个视图
	 *
	 * @param views*/
	public void setViews(List<Object> views) {
		// TODO 前后增加了两个多余的View，用来实现切换下一张
		if (views.size() <= 0) {
			views.add(R.drawable.img_banner);
		}
		List<Object> myViews = new ArrayList<>();
		myViews.add(views.get(views.size() - 1));
		myViews.addAll(views);
		myViews.add(views.get(0));
		headerViews = myViews;
		adapter = new AdsPageAdapter(headerViews);
		viewPager.setAdapter(adapter);
		viewPagerIndicator.setIndacatorCount(headerViews.size() - 2);
		numIndicator.setText(("1/"+viewPagerIndicator.getIndicatorCount()));
	}

	/**
	 * 清空数据源，达到移除图片的目的
	 * */
	public void removeViews() {

		if (null != headerViews) {
			headerViews.clear();
			adapter.notifyDataSetChanged();
			viewPagerIndicator.setIndacatorCount(0);// 将指示图片张数的indicator置为0
		}
	}

	private OnPageItemClickListener onPageItemClickListener;

	/**
	 * 监听ViewPager的page页面被点击的接口
	 * */
	public interface OnPageItemClickListener {
		public void onItemClicked(int index);
	}

	/**
	 * 设置ViewPager被点击的监听器
	 * */
	public void setOnPageItemClickListener(OnPageItemClickListener onPageItemClickListener) {
		this.onPageItemClickListener = onPageItemClickListener;
	}

	/**
	 * 设置当前的ViewPager是哪一页
	 * 
	 * @param pageIndex
	 *            页面的索引
	 * */
	public void setCurrentPage(int pageIndex) {

		if (adapter == null) {
			throw new IllegalStateException("you should call setViews(List<View> views) method first");
		}
		if (pageIndex >= adapter.getCount() || pageIndex < 0) {
			throw new IllegalArgumentException("the argument pageIndex was out of bound");
		}
		viewPager.setCurrentItem(pageIndex + 1);// 这里需要注意！因为左右加入了两个虚拟的数据，所以这里需要+1
		if (null != mScroller)
			mScroller.setDuration(VIEWPAGER_TIME);
		viewPagerIndicator.setCurrentPageIndicator(pageIndex);
		//		tvTitle.setText(adapter.getPageTitle(pageIndex + 1));// 这里需要注意！因为左右加入了两个虚拟的数据，所以这里需要+1
	}

	/**
	 * 设置是否支持循环播放，如果设置为true，则播放到最后一张的时候，回滚到第一张，重新播放，否则回滚后停留在第一张后不进行播放了。
	 * 注意：需要同时设置setAutoSlipping(true)
	 * 
	 * @param isLooper
	 *  是否支持循环播放
	 */
	public void setAutoLooper(boolean isLooper) {
		autoLooper = isLooper;
	}

	/**
	 * 是否支持自动播放
	 * 
	 * @param isAllowed
	 *            true则默认播放一次
	 */
	public void setAutoSlipping(boolean isAllowed) {
		autoPlay = isAllowed;
		startAutoSlipping();
	}

	/**
	 * 停止自动播放
	 * 
	 */
	public void stopAutoSlipping() {
		autoPlay = false;
		if (null != autoPlayHandler) {
			autoPlayHandler.removeMessages(0);
			autoPlayHandler.removeCallbacksAndMessages(null);
			autoPlayHandler = null;
		}


	}

	/**
	 * 设置循环播放图片的时间
	 * 
	 * @param looperTime
	 */
	public void setLooperTime(int looperTime) {
		LOOPER_TIME = looperTime;
	}

	/**
	 * 开始自动播放
	 * */
	public void startAutoSlipping() {

		if (null == autoPlayHandler) {
			autoPlayHandler = new AutoPlayHandler();

		}
		if (autoPlay == true) {
			autoPlayHandler.removeMessages(0);
			message = new Message();
			message.what = 0;
			autoPlayHandler.sendMessageDelayed(message, LOOPER_TIME);// 延迟两秒发送消息
		}
	}
	public void setStyle(IndicatorStyle style) {
		this.style = style;
		switch (style) {
			case NUMBER:
				rlBottom.setVisibility(GONE);
				numIndicator.setVisibility(VISIBLE);
				break;
			default:
				break;
		}
	}
	/**
	 * 自动播放句柄Handler类
	 * */
	private class AutoPlayHandler extends Handler {
		@Override
		public void handleMessage(Message msg) {
			if (autoPlay == true && viewPager != null && adapter != null && adapter.getCount() > 3)//只有一个的时候不能轮播和滑动
			{
				if (autoLooper) {
					if (null != mScroller) {
						mScroller.setDuration(VIEWPAGER_TIME);
					}
					viewPager.setCurrentItem((viewPager.getCurrentItem() + 1) % adapter.getCount());// 换页，同时实现了循环播放

				} else {
					if (viewPager.getCurrentItem() == adapter.getCount() - 1) {
						if (null != mScroller) {
							mScroller.setDuration(VIEWPAGER_TIME);
						}
						viewPager.setCurrentItem(0);
						autoPlay = false;
					} else {
						if (null != mScroller) {
							mScroller.setDuration(VIEWPAGER_TIME);
						}
						viewPager.setCurrentItem((viewPager.getCurrentItem() + 1));
					}
				}
				message = autoPlayHandler.obtainMessage(0);// 重新给message赋值，因为前一个message“还在使用中”
				sendMessageDelayed(message, LOOPER_TIME);
			}
		}
	}

	/**
	 * ViewPager的adapter
	 * */
	private class AdsPageAdapter extends PagerAdapter {

		List<Object> views;

		public AdsPageAdapter(List<Object> views) {
			if (views == null) {
				throw new IllegalArgumentException("the argument of views can not be null");
			}
			this.views = views;
			if (def_bitmap == null) {
				def_bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.img_banner);
			}
		}

		@Override
		public int getCount() {
			return views.size();
		}

		@Override
		public boolean isViewFromObject(View arg0, Object arg1) {
			return arg0 == (View) arg1;
		}

		@Override
		public Object instantiateItem(ViewGroup arg0, int position) {
			ImageView imageView = new ImageView(arg0.getContext());
			imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
			Object path = views.get(position);
//			Log.i("info", "string:--->" + path);
			//当没有设置默认显示图片的时候
			if (path instanceof String){
				String paths= (String) path;
			if (!TextUtils.isEmpty((paths))) {
				//设置默认图片
				//现在显示原图
				Pattern pattern = Pattern.compile("[0-9]*");
				Matcher isNum = pattern.matcher(paths);

				if (isNum.matches()) {
					int intPath = Integer.valueOf(paths);
					Glide.with(arg0.getContext()).load(intPath).apply(options).into(imageView);
				} else {
					Glide.with(arg0.getContext()).load(path).apply(options).into(imageView);
				}

			} else {
				//设置了默认图片,攻略焦点图
				imageView.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.img_banner));
			}
			}else {
				int paths= (int) path;
				Glide.with(arg0.getContext()).load(paths).apply(options).into(imageView);
			}
			//如果是一张，两边的填充位不加载图片。避免大图不能刷新到UI上。
			if (views.size() <= 3) {
				if (position == 0 || position == 2) {
					return imageView;
				}
			}
			arg0.addView(imageView, 0);
			return imageView;
		}

		@Override
		public int getItemPosition(Object object) {

			return super.getItemPosition(object);
		}

		@Override
		public void destroyItem(View arg0, int arg1, Object arg2) {
			((ViewPager) arg0).removeView((View) arg2);
		}

		@Override
		public String getPageTitle(int position) {
			return "";
		}
	}

	/**
	 * 设置Indicator的位置
	 * 
	 * @param layoutAlign
	 *            指定大致的位置 比如RelativeLayout.CENTER_IN_PARENT,RelativeLayout.
	 *            ALIGN_PARENT_RIGHT等
	 * @param left
	 * @param top
	 * @param right
	 * @param bottom
	 */
	public void setIndicatorLocation(int[] layoutAlign, int left, int top, int right, int bottom) {
		RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
		if (layoutAlign != null) {
			for (int align : layoutAlign) {
				lp.addRule(align);
			}
		}
//		lp.setMargins(left, top, right,bottom);//这里没有效果，需要使用
//		viewPagerIndicator.setPadding(left, top, right,bottom);

		viewPagerIndicator.setLayoutParams(lp);
		viewPagerIndicator.setPadding(left, top, right, bottom);
	}

	/**
	 * 设置Indicator之间的距离
	 * */
	public void setIndicatorPadding(int padding) {
		viewPagerIndicator.setIndicatorPaddings(padding);
	}

	/**
	 * 设置Indicator的小图标
	 * */
	public void setIndicatorDrawable(int indicatorNorRes, int indicatorSelRes) {

		viewPagerIndicator.setIndicatorIcon(indicatorNorRes, indicatorSelRes);
	}

	/**
	 * 设置Indicator的小图标
	 * */
	public void setIndicatorDrawable(Drawable indicatorNor, Drawable indicatorSel) {

		viewPagerIndicator.setIndicatorIcon(indicatorNor, indicatorSel);
	}

	/**
	 * 设置Indicator的可见性
	 * */
	public void setIndicatorVisiability(int visibility) {

		viewPagerIndicator.setVisibility(visibility);
	}
	public enum IndicatorStyle {
		NORMAL,
		NUMBER
	}

}
